<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="日期" prop="monthYear">
        <el-date-picker style="margin-right:8px" v-model="queryParams.dateSection" type="daterange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" @change="bindChangeQueryAllDate" />
      </el-form-item>
      <el-form-item label="稽核员" prop="auditor">
        <el-input v-model="queryParams.auditor" placeholder="请输入稽核员姓名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- <el-button type="primary" plain @click="bindAssign" v-hasPermi="['audit:award:add']">重新指派</el-button> -->
        <el-button type="primary" plain @click="handleAll" v-hasPermi="['audit:award:add']">重新指派</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="awardList" @selection-change="handleSelectionChange" :span-method="arraySpanMethod">
      <el-table-column label="姓名" align="center" prop="auditor" />
      <el-table-column label="路段" align="center" prop="dutyRoadName" />
      <el-table-column label="收费站" align="center" prop="dutyDeptName" />
      <el-table-column label="系统" align="center" prop="dutyPlat">
        <template #default="scope">
          <!-- <span>{{scope.row.dutyPlat }}</span> -->
          <dict-tag :options="c_auditor_duty_plat_type" :value="scope.row.dutyPlat" />
          <!-- <el-checkbox-group v-model="scope.row.dutyPlat" >
            <el-checkbox :label="item.value" :value="item.value" v-for="(item,index) in c_auditor_duty_plat_type" :key="index"> {{item.label}}</el-checkbox>
          </el-checkbox-group> -->
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="beginDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="expireDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['audit:award:edit']">指派</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['audit:award:remove']">清空</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改集中稽核对话框 -->
    <el-dialog title="重新指派" v-model="open" width="1200px" append-to-body>
      <!-- <div class="dialog-content"> -->
        <el-form ref="awardRef" :model="form" :rules="rules" label-width="120px">
          <!-- <el-row :gutter="15">
            <el-col :span="6" :xs="24">
              <div class="personnel">
                <div class="personnel-item" @click="bindChangePersonnel(index)" :class="personnelId==index?'active':''" v-for="(item,index) in personnelList"
                  :key="index">{{item.userName}}</div>
              </div>

            </el-col> 
            <el-col :span="18" :xs="24">-->
              <!-- <div class="padding-bottom">指派给{{personnelList[personnelId].userName}}的稽核工作</div> -->
              <el-form-item label="系统" prop="dutyPlat" label-width="50px" v-if="c_auditor_duty_plat_type.length>=1">
                <el-radio-group v-model="dutyPlat" size="large" @change="handleCheckedButtonsChange">
                  <el-radio-button :label="item.value" :value="item.value" v-for="(item,index) in c_auditor_duty_plat_type"
                    :key="index">{{item.label}}</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <!-- <el-carousel height="500px" arrow="never" :autoplay="false" @change="bindChangeCarousel" ref="carousel">
                <el-carousel-item v-for="item in 3" :key="item"> -->
                  <el-form-item label="时间" prop="monthYear" label-width="50px">
                    <el-date-picker v-model="dateSection" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                      @change="bindChangeAllDate" />
                  </el-form-item>
                  <div class="flex">
                    <div class="name">路段{{item}}</div>
                    <el-tree style="max-width: 100%" :data="deptOptions"
                      :default-checked-keys="defaultCheckArr" @check="bindChangeTree" show-checkbox
                      node-key="id" default-expand-all :props="{class:customNodeClass,...defaultProps}"  />
                  </div>
                <!-- </el-carousel-item>
              </el-carousel> -->

              <!-- <el-form-item label="系统" prop="dutyPlat" label-width="50px" v-if="c_auditor_duty_plat_type.length>=1">

              <el-checkbox-group v-model="form.dutyPlatArr" >
                <el-checkbox :label="item.value" :value="item.value" v-for="(item,index) in c_auditor_duty_plat_type" :key="index"> {{item.label}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item> -->
<!-- 
            </el-col>
          </el-row> -->
        </el-form>
      <!-- </div> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-hasPermi="['audit:award:edit']">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
  
  <script setup name="Award">
import moment from 'moment'
import { listcAuditorDuty, getcAuditorDuty, delcAuditorDuty, updatecAuditorDuty, clearcAuditorDuty, restartcAuditorDuty } from "@/api/charge/cAuditorDuty";
import { listCAuditor } from "@/api/charge/cAuditor";
import { deptTreeSelect } from "@/api/system/user";
import useUserStore from '@/store/modules/user'
import { watch } from 'vue';
import Index from '../personnel/index.vue';


const { proxy } = getCurrentInstance();
const { audit_work_status, c_auditor_duty_plat_type } = proxy.useDict('audit_work_status', 'c_auditor_duty_plat_type');
const userStore = useUserStore()
const awardList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dialogDoc = ref(false)
const fileViewerRef = ref(null);
const deptOptions = ref()
const disableDept = ref([])//部级
const disableRecon = ref([])//对账
const disableStat = ref([])//稽核分析
const deptId = ref()
const dateSection = ref()
const tbCentreAuditorDeptList = ref()
const personnelList = ref([])
const personnelId = ref(0)
const activeIndex = ref()
const carousel = ref()
const perInfoArr = ref([])
const dutyPlat = ref("1")
const defaultProps = ref({
  children: 'children',
  label: 'label',
  disabled: (node) => {
    let arr=dutyPlat.value==1?disableRecon.value:dutyPlat.value==2?disableDept.value:disableStat.value;
    let arr2=form.value.perInfoArr[personnelId.value]['tbCentreAuditorDeptList'+dutyPlat.value];
    // console.log(arr2,form.value.perInfoArr[personnelId.value])
    //根据需求判断是否禁用 &&!arr2.includes(node.id)
    if (arr.includes(node.id)&&!arr2.includes(node.id)) {
      return true;//不禁用
    } else {
      return false;//禁用
    }
  }
})
const defaultCheckArr=ref([])
const data = reactive({
  form: { perInfoArr: [] },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
  },
  rules: {
  }
});


const arraySpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (columnIndex === 0 || columnIndex === 6) {
    const currentValue = row["auditor"];
    // 获取上一行相同列的值
    const preRow = awardList.value[rowIndex - 1];
    const preValue = preRow ? preRow["auditor"] : null;
    if (currentValue === preValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      // 否则计算当前单元格应该跨越多少行
      let rowspan = 1;
      for (let i = rowIndex + 1; i < awardList.value.length; i++) {
        const nextRow = awardList.value[i];
        const nextValue = nextRow["auditor"];
        if (nextValue === currentValue) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    }
  }

  if (columnIndex === 1) {
    const currentValue = row["dutyRoadName"];
    if (!currentValue) return;
    // 获取上一行相同列的值
    const preRow = awardList.value[rowIndex - 1];
    const preValue = preRow ? preRow["dutyRoadName"] : null;
    if (currentValue === preValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      // 否则计算当前单元格应该跨越多少行
      let rowspan = 1;
      for (let i = rowIndex + 1; i < awardList.value.length; i++) {
        const nextRow = awardList.value[i];
        const nextValue = nextRow["dutyRoadName"];
        if (nextValue === currentValue) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    }
  }



}

const customNodeClass = (data, node) => {
  if (data.children) {
    return 'is-penultimate'
  }
  return null
}
const { queryParams, form, rules } = toRefs(data);
// const defaultCheckArr= computed(()=>{
//   let arr=form.value.perInfoArr[personnelId.value]['tbCentreAuditorDeptList'+dutyPlat.value];
//   return arr;
// })
watch(()=>dutyPlat.value,val=>{
  defaultCheckArr.value=form.value.perInfoArr[personnelId.value]['tbCentreAuditorDeptList'+val];
},{deep:true})

function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data[0].children[0].children;
  });
};

/** 查询集中稽核列表 */
function getList() {
  loading.value = true;
  listcAuditorDuty(queryParams.value).then(response => {
    awardList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getPersonnelList() {
  loading.value = true;
  listCAuditor({ pageNum: 1, pageSize: 10000 }).then(response => {
    personnelList.value = response.rows;
    loading.value = false;
    personnelList.value.forEach((element,index) => {
      form.value.perInfoArr[index]={tbCentreAuditorDeptList1:[],tbCentreAuditorDeptList2:[],tbCentreAuditorDeptList3:[]}
    });
    
  });
}
const bindAssign = () => {
  // 重新指派
  restartcAuditorDuty().then(res => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("重新指派成功");
    }

  })
}
const bindChangeTree = (val, list) => {
  // form.value.tbCentreAuditorDeptList = list.checkedKeys
  form.value.perInfoArr[personnelId.value]['tbCentreAuditorDeptList' + dutyPlat.value] = list.checkedKeys;
  if (dutyPlat.value == '1') {
    disableRecon.value = list.checkedKeys;
  } else if (dutyPlat.value == '2') {
    disableDept.value = list.checkedKeys
  } else if (dutyPlat.value == '3') {
    disableStat.value = list.checkedKeys
  }
}
const bindChangeAllDate = (val) => {
  if (!val) { dateSection.value = []; queryParams.value.startDate = ''; queryParams.value.endDate = ''; return }
  dateSection.value = [moment(val[0]).format("YYYY-MM-DD"), moment(val[1]).format("YYYY-MM-DD")]
  form.value.perInfoArr[personnelId.value].beginDate = dateSection.value[0];
  form.value.perInfoArr[personnelId.value].expireDate = dateSection.value[1];
}
const bindChangePersonnel = (index) => {
  personnelId.value = index;
  form.value.perInfoArr[personnelId.value].auditor = personnelList.value[index].userName;
  form.value.perInfoArr[personnelId.value].auditorId = personnelList.value[index].userId;
}
const bindChangeQueryAllDate = (val) => {
  queryParams.value.dateSection = [moment(val[0]).format("YYYY-MM-DD"), moment(val[1]).format("YYYY-MM-DD")]
  queryParams.value.beginDate = queryParams.value.dateSection[0];
  queryParams.value.expireDate = queryParams.value.dateSection[1];
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    perInfoArr: []
  };
  proxy.resetForm("awardRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {

  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
  }
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const handleAll = () => {
  open.value = true;

}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加集中稽核";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getcAuditorDuty(_id).then(response => {
    form.value = response.data;
    form.value.dutyPlatArr = form.value.dutyPlat && form.value.dutyPlat.indexOf(',') != -1 ? form.value.dutyPlat.split(',') : [form.value.dutyPlat]
    form.value.tbCentreAuditorDeptList = form.value.dutyDeptIds;
    open.value = true;
    title.value = "修改集中稽核";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["awardRef"].validate(valid => {
    if (valid) {
      if (!form.value.dutyPlatArr[0]) {
        form.value.dutyPlatArr.shift()
      }
      form.value.dutyPlat = form.value.dutyPlatArr && form.value.dutyPlatArr.length > 1 ? form.value.dutyPlatArr.join(',') : form.value.dutyPlatArr[0]
      updatecAuditorDuty(form.value).then(response => {
        proxy.$modal.msgSuccess("指派成功");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除集中稽核编号为"' + _ids + '"的数据项？').then(function () {
    return clearcAuditorDuty(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('audit/award/export', {
    ...queryParams.value
  }, `稽核指派_${new Date().getTime()}.xlsx`)
}

const handleCheckedButtonsChange = (val) => {
  carousel.value.setActiveItem(val)
  dutyPlat.value = val;
  // form.value.perInfoArr[personnelId.value].dutyPlat
}
const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptId.value = res.user.dept.deptId;
    }
  })
}

getDeptTree()
getDeptId()
getList()
getPersonnelList()
  </script>
  
   <style scoped>
.flex {
  display: flex;
}
.flex .name {
  width: 40px;
  flex-shrink: 0;
  padding-top: 10px;
  font-weight: 600;
}
</style> 
  <style >
.is-penultimate > .el-tree-node__content {
  height: 40px;
  line-height: 40px;
  font-weight: 600;
  /* color: #626aef; */
  background: #f5f5f5;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #dedede;
}
.el-tree .el-tree-node.is-penultimate > .el-tree-node__children .el-tree-node {
  padding: 5px 0;
}
.el-tree .el-tree-node.is-penultimate > .el-tree-node__children {
  display: flex;
  flex-direction: row;
}
.el-tree
  .el-tree-node.is-penultimate
  > .el-tree-node__children
  .el-tree-node
  .el-tree-node__content {
  padding-left: 0 !important;
}
.el-tree .el-tree-node.is-penultimate > .el-tree-node__children {
  flex-wrap: wrap;
}
.is-penultimate > .el-tree-node__children > div {
  width: 25%;
}
.padding-bottom {
  padding-bottom: 20px;
}
.personnel {
  width: 100%;
  height: 100%;
  background: #f3f5f7;
  padding: 20px;
  box-sizing: border-box;
  border-radius: 10px;
}
.personnel .personnel-item {
  line-height: 2.2;
  font-size: 16px;
  padding: 0 10px;
  border-radius: 10px;
  cursor: pointer;
  margin-bottom: 15px;
  text-align: center;
}
.personnel .personnel-item.active {
  background: var(--el-color-primary);
  color: #fff;
}
.dialog-content {
  height: 600px;
  /* overflow-y:scroll ; */
}
</style>
  